
package cn.nubia.admin.application.service;

import cn.nubia.admin.application.bean.*;
import cn.nubia.admin.application.query.SoftItemQuery;
import cn.nubia.admin.sysconfig.bean.Category;
import cn.nubia.admin.sysconfig.bean.SystemLog;
import cn.nubia.admin.sysconfig.service.CategoryService;
import cn.nubia.admin.common.mybatis.bean.Paged;
import cn.nubia.admin.common.mybatis.bean.Query;
import cn.nubia.admin.common.mybatis.service.BaseServiceImpl;
import cn.nubia.admin.common.springmvc.WebContext;
import cn.nubia.admin.common.utils.DateUtil;
import cn.nubia.admin.sysconfig.service.SystemLogService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * Created by justin on 15/6/30.
 */
@Service
public class SoftItemService extends BaseServiceImpl<SoftItem> {

    @Autowired
    private TerminalService terminalService;
    @Autowired
    private SoftService softService;
    @Autowired
    CategoryService categoryService;
    @Autowired
    SystemLogService systemLogService;

    /**
     * 根据查询条件查询softItem列表
     *
     * @return
     */
    public Paged<SoftUSoftItem> findPagedList(SoftItemQuery softQuery) {
        String sql = getQuerySql(softQuery);
        Paged<SoftUSoftItem> items = findPageBySql(sql, SoftUSoftItem.class, softQuery.getPageNo(), softQuery.getPageSize());
        setCategoryName(items);
        return items;
    }

    public List<SoftUSoftItem> findList(SoftItemQuery softQuery){
        String sql = getQuerySql(softQuery);
        return findBySql(sql,SoftUSoftItem.class);
    }

    private void setCategoryName(Paged<SoftUSoftItem> itemPaged){
        if(itemPaged.getListData()!=null){
            for(SoftUSoftItem softUSoftItem : itemPaged.getListData()){
                softUSoftItem.initCategoryName(categoryService.getCategoryConstruct(softUSoftItem.getCategoryId()));
            }
        }

    }

    private String getQuerySql(SoftItemQuery softQuery){
        String sql = "select a.soft_id as softId, " +
                " b.soft_item_id as softItemId, " +
                " a.soft_name as softName, " +
                " a.package_name as packageName, " +
                " b.version_name as versionName, " +
                " b.download_number as vdownloadNumber, " +
                " b.state as state, " +
                " b.icon_url as iconUrl, " +
                " a.category_id as categoryId, " +
                " b.is_last_version as isLastVersion, " +
                " b.check_admin_name as checkAdminName, " +
                " b.publish_time as publishTime " +
                "from nb_soft a ,nb_soft_item b where a.soft_id = b.soft_id  ";
        String condition = "";
        if (softQuery.getSoftId() != null && softQuery.getSoftId() > 0) {
            condition += " AND  a.soft_id = " + softQuery.getSoftId();
        }
        if (softQuery.getSoftItemId() != null && softQuery.getSoftItemId() > 0) {
            condition += " AND  b.soft_item_id = " + softQuery.getSoftItemId();
        }
        if (softQuery.getItemName() != null && softQuery.getItemName() != "") {
            condition += " AND  b.item_name like '%" + softQuery.getItemName() + "%' ";
        }
        if (softQuery.getPackageName() != null && softQuery.getPackageName() != "") {
            condition += " AND  a.package_name like '%" + softQuery.getPackageName() + "%' ";
        }

        if (softQuery.getCheckAdminName() != null && softQuery.getCheckAdminName() != "") {
            condition += " AND  a.check_admin_name like '%" + softQuery.getCheckAdminName() + "%' ";
        }

        if (softQuery.getCheckAdminId() != null && softQuery.getCheckAdminId() > 0) {
            condition += " AND  b.check_admin_id = " + softQuery.getCheckAdminId();
        }

        if (softQuery.getState() != null && softQuery.getState() != -99) {
            condition += " AND  b.state = " + softQuery.getState();
        } else {
            condition += " AND  b.state != -1 ";
        }
        if (softQuery.getSafeState() != null && softQuery.getSafeState() != -99) {
            condition += " AND  b.is_safe = " + softQuery.getSafeState();
        }
        if (softQuery.getSoftSrc() != null && softQuery.getSoftSrc() != -99) {
            condition += " AND  b.soft_src = " + softQuery.getSoftSrc();
        }


        if (softQuery.getCategoryId3() != null && softQuery.getCategoryId3() > 0) {
            condition += " AND  a.category_id = " + softQuery.getCategoryId3();
        } else if (softQuery.getCategoryId2() != null && softQuery.getCategoryId2() > 0) {
            condition += " AND  a.category_parent_id = " + softQuery.getCategoryId2();
        }else if (softQuery.getCategoryId() != null && softQuery.getCategoryId() > 0) {
            String secCategories ="";
            List<Category> categories=categoryService.getSubCategoryList(softQuery.getCategoryId());
            for(int i=0;i<categories.size();i++){
                secCategories+=categories.get(i).getId();
                if(i!=categories.size()-1)secCategories+=",";
            }
            condition += " AND  a.category_parent_id in (" + secCategories+") ";
        }

        if (softQuery.getIsAccredit() != null && softQuery.getIsAccredit() != -99) {
            condition += " AND  a.is_accredit = " + softQuery.getIsAccredit();
        }

        if (softQuery.getPayType() != null && softQuery.getPayType() != -99) {
            condition += " AND  b.pay_type = " + softQuery.getPayType();
        }

        if (softQuery.getPublishs() != null) {
            condition += " AND  b.publish_time >= " + DateUtil.getIntegerTime(softQuery.getPublishs()) + " ";
        }

        if (softQuery.getPublishe() != null) {
            condition += " AND  b.publish_time <= " + DateUtil.getIntegerTime(softQuery.getPublishe()) + " ";
        }
        sql += condition;

        String order = "";
        order += " order by b.publish_time desc,b.create_time desc ";
        sql += order;
        return sql;
    }


    /**
     * 删除指定的softItem
     *
     * @param id
     * @return
     */
    public boolean delSoftItem(Integer id) {
        Integer adminId = WebContext.getCachedUser().getId();//WebContext.getCachedUser().getId()
        String  adminName = WebContext.getCachedUser().getName();//WebContext.getCachedUser().getName()
        Integer curr = DateUtil.getCurrentTime();
        SoftItem softItem = get(id);
        boolean isChecked = softItem.getState() == SoftItem.STATE_CHECKED;
        softItem.setState(SoftItem.STATE_DELETE);
        softItem.setLastModifyTime(curr);
        softItem.setCheckAdminId(adminId);
        softItem.setCheckAdminName(adminName);
        softItem.setCheckTime(curr);
        update(softItem);
        if (isChecked) {
            checkForTheLastVersion(null, softItem);
        }
        systemLogService.log(SystemLog.ModuleTypeEnum.LISTSOFTITEMS, SystemLog.OperateTypeEnum.DEL, softItem.getId());
        return true;
    }

    public boolean changeState(Integer id, Integer state) {
        SoftItem softItem = get(id);
        softItem.setState(state);
        Integer adminId = WebContext.getCachedUser().getId();//WebContext.getCachedUser().getId()
        String  adminName = WebContext.getCachedUser().getName();//WebContext.getCachedUser().getName()
        Integer curr = DateUtil.getCurrentTime();
        if (state == SoftItem.STATE_CHECKED ) {
            softItem.setPublishTime(curr);
            systemLogService.log(SystemLog.ModuleTypeEnum.LISTSOFTITEMS, SystemLog.OperateTypeEnum.CHECK, softItem.getId());
        }else if(state  == SoftItem.STATE_HIDDEN){
            systemLogService.log(SystemLog.ModuleTypeEnum.LISTSOFTITEMS, SystemLog.OperateTypeEnum.HIDDEN, softItem.getId());
        }else if(state == SoftItem.STATE_DOWN){
            systemLogService.log(SystemLog.ModuleTypeEnum.LISTSOFTITEMS, SystemLog.OperateTypeEnum.DOWN, softItem.getId());
        }
        softItem.setLastModifyTime(curr);
        softItem.setCheckAdminId(adminId);
        softItem.setCheckAdminName(adminName);
        softItem.setCheckTime(curr);
        update(softItem);
        checkForTheLastVersion(null, softItem);
        return true;
    }

    /**
     * 对最新版本进行处理
     *
     * @param soft
     * @param softItem
     */
    public Soft checkForTheLastVersion(Soft soft, SoftItem softItem) {
        if (soft == null) {
            soft = softService.get(softItem.getSoftId());
        }
        //获取最新版本softItem的id
        Query<SoftItem> query = Query.build(SoftItem.class);
        query.addEq(SoftItem.COLUMN_STATE, SoftItem.STATE_CHECKED);
        query.addEq(SoftItem.COLUMN_SOFTID, soft.getId());
        query.addOrder(SoftItem.COLUMN_VERSIONCODE, Query.DBOrder.DESC);
        query.addOrder(SoftItem.COLUMN_PUBLISH, Query.DBOrder.DESC);
        SoftItem lastestItem = get(query);
        if(lastestItem==null){
            //最后一个版本被删
            soft.setLastSoftItemId(0);
            Integer curr = DateUtil.getCurrentTime();
            soft.setLastModifyTime(curr);
            softService.update(soft);
            return soft;
        }
        soft.setLastSoftItemId(lastestItem.getId());
        softService.update(soft);
        updateOtherSoftItemLastVersion(soft.getId());
        if(softItem.getId().intValue() == lastestItem.getId().intValue()){
            softItem.setIsLastVersion(SoftItem.LAST_VERSION);
            Integer curr = DateUtil.getCurrentTime();
            softItem.setLastModifyTime(curr);
            update(softItem);
        }
        return soft;
    }

    public void updateOtherSoftItemLastVersion(Integer softId){
        Query query = Query.build(SoftItem.class);
        query.addEq(SoftItem.COLUMN_SOFTID, softId);
        query.addEq(SoftItem.COLUMN_ISLASTVERSION, SoftItem.LAST_VERSION);
        SoftItem softItem = get(query);
        if(softItem!=null){
            softItem.setIsLastVersion(SoftItem.NOT_LAST_VERSION);
            Integer curr = DateUtil.getCurrentTime();
            softItem.setLastModifyTime(curr);
            update(softItem);
        }
    }

    public void delSoftItemBySoftId(Integer softId) {
        Query query = Query.build(SoftItem.class);
        query.addEq(SoftItem.COLUMN_SOFTID, softId);
        List<SoftItem> softItemList = findByQuery(query);
        for(SoftItem item : softItemList){
            item.setState(SoftItem.STATE_DELETE);
            Integer curr = DateUtil.getCurrentTime();
            item.setLastModifyTime(curr);
            update(item);
            systemLogService.log(SystemLog.ModuleTypeEnum.LISTSOFTITEMS, SystemLog.OperateTypeEnum.DEL, item.getId());
        }
    }

    public SoftItem getByVersion(Integer softId, Integer versionCode) {
        Query<SoftItem> query = Query.build(SoftItem.class);
        query.addEq(SoftItem.COLUMN_SOFTID,softId);
        query.addEq(SoftItem.COLUMN_VERSIONCODE,versionCode);
        return get(query);
    }

    public boolean checkNoItem(Integer itemId, String checkReason) {
        SoftItem softItem = get(itemId);
        Integer adminId = WebContext.getCachedUser().getId();//WebContext.getCachedUser().getId()
        String  adminName = WebContext.getCachedUser().getName();//WebContext.getCachedUser().getName()
        Integer curr = DateUtil.getCurrentTime();
        softItem.setState(SoftItem.STATE_CHECK_NO);
        softItem.setCheckAdminId(adminId);
        softItem.setCheckAdminName(adminName);
        softItem.setCheckTime(curr);
        softItem.setCheckReason(checkReason);
        softItem.setLastModifyTime(curr);
        update(softItem);
        systemLogService.log(SystemLog.ModuleTypeEnum.LISTSOFTITEMS, SystemLog.OperateTypeEnum.CHECKNO, softItem.getId());
        return true;
    }
}

